package com.tanhua.service;

import com.tanhua.dao.DashboardDao;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DashboardService {

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    DashboardDao dashboardDao;
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    private  Date date = new Date();
    private static long days = (1000 * 60) * 60 * 24;


    public Map finddashboarddata() {

        Map<String, Integer> map = new HashMap<String, Integer>();
        /**
         * 查询累计用户数量
         */
        Integer all = dashboardDao.findAll();
        map.put("cumulativeUsers", all);
        /**
         * 查询30天之内活跃用户
         */
        Integer integer = findin30dayactive();
        map.put("activePassMonth", integer);
        /**
         * 查询7天之内活跃用户
         */
        Integer integer1 = find7BeforeActive();
        map.put("activePassWeek", integer);
        /**
         * 查询今日新增用户
         */
        Integer integer2 = findtodaynewadd();
        map.put("newUsersToday", integer);
        /**
         * 查询今日新增用户涨跌率
         */
        Integer integer3 = findtodayrate();

        map.put("newUsersTodayRate", integer3);
        /**
         * 查询今日登录次数
         */
        Integer findtodaylogin = findtodaylogin();
        map.put("loginTimesToday",findtodaylogin);
        /**
         * 查询今日登录次数涨跌率
         */
        Integer findtodayloginrate= findtodayloginrate();
        map.put("loginTimesTodayRate", findtodayloginrate);
        /**
         * 查询今日活跃用户
         */
        Integer i=  findtodayactive();
        map.put("activeUsersToday", i);
        /**
         * 查询今日活跃用户涨跌率
         */
        Integer findtodayactiverate=findtodayactiverate();
        map.put("activeUsersTodayRate", findtodayactiverate);


        map.put("useTimePassWeek", integer);
        /**
         * 查询昨天活跃用户
         */
       Integer findyesterdayactive= findyesterdayactive();
        map.put("activeUsersYesterday", findyesterdayactive);
        /**
         * 查询昨天活跃用户涨跌率
         */
      Integer integer4=  findyesterdayactiverate();
        map.put("activeUsersYesterdayRate", integer4);


        return map;
    }



    public HashMap<String, List<Map<String, Integer>>> findaddactivekeep(Map<String, Object> map) {

        String type = (String) map.get("type");

        if (("101").equals(type)){
            HashMap<String, List<Map<String, Integer>>> hashMap = findscopeadd(map);
            return hashMap;
        }else if (("102").equals(type)){
            HashMap<String, List<Map<String, Integer>>> hashMap=    findscopeactive(map);
            return hashMap;
        }else if (("103").equals(type)){
            HashMap<String, List<Map<String, Integer>>> hashMap=    findscopenextdaykeep(map);
            return hashMap;
        }else {
            return null;
        }


    }























    private HashMap<String, List<Map<String, Integer>>> findscopenextdaykeep(Map<String, Object> map) {
        HashMap<String, List<Map<String, Integer>>> hashMap = new HashMap<String, List<Map<String, Integer>>>();
        ArrayList< Map<String, Integer>> list = new ArrayList<>();
        ArrayList< Map<String, Integer>> list2 = new ArrayList<>();

        String sd = (String) map.get("sd");     //获得查询开始时间     2020-04-23   --2021-04-22
        String[] split = sd.split("-");  //                     2020 05 11

        Calendar cal = Calendar.getInstance();
        String year = split[0];                         // 获得年份 2020
        String monthh = split[1];                        // 获得月份 04
        String day = split[2];                          // 获得天   23

        int dayint = Integer.parseInt(day);         //   天转换为int
        Boolean b=false;

        for (int i = 0; i < 12; i++) {          // 需要给前台返回12个月份对应的值   封装返回对象里的数据要封装12次
            HashMap<String, Integer> hashMap1 = new HashMap<>();
            int yearint = Integer.parseInt(year);           //   年份转换为int
            int monthintt = Integer.parseInt(monthh)+i;         //   月份转换为int
            int monthint=monthintt>12?monthintt-12:monthintt;
            String month= monthint<10? "-0"+monthint:"-" +monthint;

            cal.set(yearint,monthint-1,1);
            int maxday = cal.getActualMaximum(Calendar.DATE);   //获得2020-04  对应的月份有多少天

            ArrayList<String> arrayList = new ArrayList<>();    //用来保存 每天留存率
            if (b){
                dayint=1;
            }
            while (dayint<=maxday){
              String daystring = dayint<10?"-0"+dayint:"-"+dayint;

                String  findargs= year+month+daystring;
            Integer addinteger=    dashboardDao.findnextdaykeep( findargs);//查询留存了多少人


                //查询前一天的注册人数
                if (dayint==1){                    //如果当前查询参数为当月的第一天那么要查询上一个月最后一天的注册完数量来计算留存率
                    if (monthint==1){              //并且月份是1月的话那么要查询上一个年最后一月份最后一天的注册完数量来计算留存率
                        int i1 = yearint - 1;       //把对应的年份-1    2020-1   ==2019
                        String s = String.valueOf(i1);      //    2019
                        String s1 = s + "-12-31";           //   2019-12-31
                        Integer keepinteger = dashboardDao.findtodaynewadd(s1);//得到前一天的注册人数
                        NumberFormat numberFormat = NumberFormat.getInstance();
                        numberFormat.setMaximumFractionDigits(0);           //保留小数位数
                        String keeprate=null;
                        if (addinteger!=0){
                            keeprate = numberFormat.format((float) addinteger / (float) keepinteger * 100); // 的到这一天的注册留存率
                            //todo 留存率处理
                            arrayList.add(keeprate);
                        }else {
                            arrayList.add("0");
                        }

                    }else {                             // 5-1   -->     4-?
                        int i1 = monthint - 1;
                        Calendar calendar = Calendar.getInstance();
                        calendar.set(yearint,i1-1,1);
                        String addi=  i1 <10? "-0"+i1:"-"+i1;
                        int lastmonthmaxday = calendar.getActualMaximum(Calendar.DATE); //4月   30
                        String addday=  lastmonthmaxday <10? "-0"+lastmonthmaxday:"-"+lastmonthmaxday;

                        String ss= year +""+ addi+addday;  // 2020-04-30

                        Integer integer = dashboardDao.findtodaynewadd(ss);//的到前一天的注册人数
                        NumberFormat numberFormat = NumberFormat.getInstance();
                        numberFormat.setMaximumFractionDigits(0);           //保留小数位数

                        String keeprate=null;
                        if (addinteger!=0){
                             keeprate = numberFormat.format((float) addinteger / (float) integer * 100); // 的到这一天的注册留存率
                            //todo 留存率处理
                            arrayList.add(keeprate);
                        }else {
                            arrayList.add("0");
                        }



                    }
                }else {     // dayint 不是1
                    int i1 = dayint - 1;
                    String addi=  i1 <10? "-0"+i1:"-"+i1;

                    String ss= year + month+"-"+addi;           //2020-04-24    -->    2020-04-23

                    Integer integer = dashboardDao.findtodaynewadd(ss);//的到前一天的注册人数
                    NumberFormat numberFormat = NumberFormat.getInstance();
                    numberFormat.setMaximumFractionDigits(0);           //保留小数位数


                    String keeprate=null;
                    if (addinteger!=0){
                        keeprate = numberFormat.format((float) addinteger / (float) integer * 100); // 的到这一天的注册留存率
                        //todo 留存率处理
                        arrayList.add(keeprate);
                    }else {
                        arrayList.add("0");
                    }


                }
                dayint++;
            }
            // 例如 2020-04-24   2020-04-25  2020-04-26  2020-04-27  2020-04-28
            //      2020-04-29   2020-04-30
            //都保存了之后  拿出来计算
            int i2=0;
            for (int i1 = 0; i1 < arrayList.size(); i1++) {

                 i2 += Integer.parseInt(arrayList.get(i1));    //每天的留存率总和

            }
            Integer v =  i2 / arrayList.size();      //留存率的总和除以几天 ,得到这个月的平均次日留存率
            Integer i1 = Integer.parseInt(month);
            hashMap1.put("title",i1)      ;     // 保存这个月
            hashMap1.put("amount",v) ;          // 保存这个月的次日留存率
            list.add(hashMap1);
            //修改标记
            b=true;
        }
        hashMap.put("thisYear",list);


        int lasti = Integer.parseInt(year);// 获得年份 2020
        lasti -=1;                         //  获得开始年份的去年年份
        String year1 = String.valueOf(lasti);
        for (int itwo = 0; itwo < 12; itwo++) {          // 需要给前台返回12个月份对应的值   封装返回对象里的数据要封装12次
            HashMap<String, Integer> hashMap1 = new HashMap<>();
            int yearint = Integer.parseInt(year1);           //   年份转换为int
            int monthintt = Integer.parseInt(monthh)+itwo;         //   月份转换为int
            int monthint=monthintt>12?monthintt-12:monthintt;
            String month= monthint<10? "-0"+monthint:"-" +monthint;

            cal.set(yearint,monthint-1,1);
            int maxday = cal.getActualMaximum(Calendar.DATE);   //获得2020-04  对应的月份有多少天

            ArrayList<String> arrayList = new ArrayList<>();    //用来保存 每天留存率
            if (b){
                dayint=1;
            }
            while (dayint<=maxday){
                String daystring = dayint<10?"-0"+dayint:"-"+dayint;

                String  findargs= year1+month+daystring;
                Integer addinteger=    dashboardDao.findnextdaykeep( findargs);//查询留存了多少人


                //查询前一天的注册人数
                if (dayint==1){                    //如果当前查询参数为当月的第一天那么要查询上一个月最后一天的注册完数量来计算留存率
                    if (monthint==1){              //并且月份是1月的话那么要查询上一个年最后一月份最后一天的注册完数量来计算留存率
                        int i1 = yearint - 1;       //把对应的年份-1    2020-1   ==2019
                        String s = String.valueOf(i1);      //    2019
                        String s1 = s + "-12-31";           //   2019-12-31
                        Integer keepinteger = dashboardDao.findtodaynewadd(s1);//得到前一天的注册人数
                        NumberFormat numberFormat = NumberFormat.getInstance();
                        numberFormat.setMaximumFractionDigits(0);           //保留小数位数


                        String keeprate=null;
                        if (addinteger!=0){
                            keeprate = numberFormat.format((float) addinteger / (float) keepinteger * 100); // 的到这一天的注册留存率
                            //todo 留存率处理
                            arrayList.add(keeprate);
                        }else {
                            arrayList.add("0");
                        }



                    }else {                             // 5-1   -->     4-?

                        int i1 = monthint - 1;
                        Calendar calendar = Calendar.getInstance();
                        calendar.set(yearint,monthint-1-1,1);

                        int lastmonthmaxday = cal.getActualMaximum(Calendar.DATE); //4月   30
                        String addi=  i1 <10? "-0"+i1:"-"+i1;
                        String addday=  lastmonthmaxday <10? "-0"+lastmonthmaxday:"-"+lastmonthmaxday;
                        String ss= year1 + addi+addday;  // 2020-04-30

                        Integer integer = dashboardDao.findtodaynewadd(ss);//的到前一天的注册人数
                        NumberFormat numberFormat = NumberFormat.getInstance();
                        numberFormat.setMaximumFractionDigits(0);           //保留小数位数



                        String keeprate=null;
                        if (addinteger!=0){
                            keeprate = numberFormat.format((float) addinteger / (float) integer * 100); // 的到这一天的注册留存率
                            //todo 留存率处理
                            arrayList.add(keeprate);
                        }else {
                            arrayList.add("0");
                        }




                    }
                }else {     // dayint 不是1
                    int i1 = dayint - 1;
                    String addi=  i1 <10? "-0"+i1:"-"+i1;


                    String ss= year1 + month+addi;           //2020-04-24    -->    2020-04-23


                    Integer integer = dashboardDao.findtodaynewadd(ss);//的到前一天的注册人数
                    NumberFormat numberFormat = NumberFormat.getInstance();
                    numberFormat.setMaximumFractionDigits(0);           //保留小数位数



                    String keeprate=null;
                    if (addinteger!=0){
                        keeprate = numberFormat.format((float) addinteger / (float) integer * 100); // 的到这一天的注册留存率
                        //todo 留存率处理
                        arrayList.add(keeprate);
                    }else {
                        arrayList.add("0");
                    }

                }
                dayint++;
            }
            // 例如 2020-04-24   2020-04-25  2020-04-26  2020-04-27  2020-04-28
            //      2020-04-29   2020-04-30
            //都保存了之后  拿出来计算
            int i2=0;
            for (int i1 = 0; i1 < arrayList.size(); i1++) {

                i2 += Integer.parseInt(arrayList.get(i1));    //每天的留存率总和

            }
            Integer v =  i2 / arrayList.size();      //留存率的总和除以几天 ,得到这个月的平均次日留存率
            Integer i1 = Integer.parseInt(month);
            hashMap1.put("title",i1)      ;     // 保存这个月
            hashMap1.put("amount",v) ;          // 保存这个月的次日留存率
            list2.add(hashMap1);
            //修改标记
            b=true;
        }

        hashMap.put("lastYear",list2);
        return hashMap;
    }


    private HashMap<String, List<Map<String, Integer>>> findscopeactive(Map<String, Object> map) {

        HashMap<String, List<Map<String, Integer>>> hashMap =new HashMap<String, List<Map<String, Integer>>>();
        ArrayList<Map<String, Integer>> list = new ArrayList<>();


        String sd = (String) map.get("sd");    //获得请求参数里的开始时间   2020-05-24
        String[] split = sd.split("-"); //对时间字符串进行分割得到   2020 05 24
        int i1 = Integer.parseInt(split[1]);   //获得int类型月份  5

        for (int i = 0; i < 12; i++) {          //查询开始时间后的一年的数据
            int i2 = i1 + i;                    //对月份进行迭代

            int  i3=  i2>12?i2-12:i2;        //如果得到的月份值大于12就减去12确保查询参数在1到12范围内
            String s=i3<10? "-0"+i3:"-"+i3; //如果得到的月份小于10的话需要拼接一个-0不然在数据库查询不到数据

            String findsmallarg=split[0]+s+"-01";   //拼接出查询语句的范围最小的日期
            String findbigarg=split[0]+s+"-31";     //拼接出查询语句的范围最大的日期

            Integer integer=   dashboardDao.findscopeactive(findsmallarg,findbigarg); //对查询条件进行查询
            HashMap<String, Integer> hMap = new HashMap<>();
            hMap.put("title",i3);
            hMap.put("amount",integer);

            list.add(hMap);
        }
        hashMap.put("thisYear",list);


        ArrayList<Map<String, Integer>> list2 = new ArrayList<>();

        int year = Integer.parseInt(split[0]);  //获得int类型月份  2020
        int lastyear=year-1;                     //获得查询条件的开始时间的去年时间 2019
        String lastyearstring=lastyear+"";      // 获得查询条件的开始时间的去年时间得字符串

        for (int i = 0; i < 12; i++) {          //查询开始时间后的一年的数据
            int i2 = i1 + i;                    //对月份进行迭代

            int  i3=  i2>12?i2-12:i2;        //如果得到的月份值大于12就减去12确保查询参数在1到12范围内
            String s=i3<10? "-0"+i3:"-"+i3; //如果得到的月份小于10的话需要拼接一个-0不然在数据库查询不到数据

            String findsmallarg=lastyearstring+s+"-01";   //拼接出查询语句的范围最小的日期
            String findbigarg=lastyearstring+s+"-31";     //拼接出查询语句的范围最大的日期

            Integer integer=   dashboardDao.findscopeactive(findsmallarg,findbigarg); //对查询条件进行查询
            HashMap<String, Integer> hMap = new HashMap<>();

            hMap.put("title",i3);
            hMap.put("amount",integer);
            list2.add(hMap);
        }

        hashMap.put("lastYear",list2);
        return hashMap;


    }


    private HashMap<String, List<Map<String, Integer>>> findscopeadd(Map<String, Object> map) {
        HashMap<String, List<Map<String, Integer>>> hashMap =new HashMap<String, List<Map<String, Integer>>>();
        ArrayList<Map<String, Integer>> list = new ArrayList<>();


        String sd = (String) map.get("sd");    //获得请求参数里的开始时间   2020-05-24
        String[] split = sd.split("-"); //对时间字符串进行分割得到   2020 05 24
        int i1 = Integer.parseInt(split[1]);   //获得int类型月份  5

        for (int i = 0; i < 12; i++) {          //查询开始时间后的一年的数据
            int i2 = i1 + i;                    //对月份进行迭代

                int  i3=  i2>12?i2-12:i2;        //如果得到的月份值大于12就减去12确保查询参数在1到12范围内
                String s=i3<10? "-0"+i3:"-"+i3; //如果得到的月份小于10的话需要拼接一个-0不然在数据库查询不到数据

                String findsmallarg=split[0]+s+"-01";   //拼接出查询语句的范围最小的日期
                String findbigarg=split[0]+s+"-31";     //拼接出查询语句的范围最大的日期

         Integer integer=   dashboardDao.findscopeadd(findsmallarg,findbigarg); //对查询条件进行查询
            HashMap<String, Integer> hMap = new HashMap<>();
            hMap.put("title",i3);
            hMap.put("amount",integer);

            list.add(hMap);
        }
        hashMap.put("thisYear",list);


        ArrayList<Map<String, Integer>> list2 = new ArrayList<>();

       int year = Integer.parseInt(split[0]);  //获得int类型月份  2020
       int lastyear=year-1;                     //获得查询条件的开始时间的去年时间 2019
        String lastyearstring=lastyear+"";      // 获得查询条件的开始时间的去年时间得字符串

        for (int i = 0; i < 12; i++) {          //查询开始时间后的一年的数据
            int i2 = i1 + i;                    //对月份进行迭代

            int  i3=  i2>12?i2-12:i2;        //如果得到的月份值大于12就减去12确保查询参数在1到12范围内
            String s=i3<10? "-0"+i3:"-"+i3; //如果得到的月份小于10的话需要拼接一个-0不然在数据库查询不到数据

            String findsmallarg=lastyearstring+s+"-01";   //拼接出查询语句的范围最小的日期
            String findbigarg=lastyearstring+s+"-31";     //拼接出查询语句的范围最大的日期

            Integer integer=   dashboardDao.findscopeadd(findsmallarg,findbigarg); //对查询条件进行查询
            HashMap<String, Integer> hMap = new HashMap<>();

            hMap.put("title",i3);
            hMap.put("amount",integer);
            list2.add(hMap);
        }

        hashMap.put("lastYear",list2);
        return hashMap;
    }















    private Integer findyesterdayactiverate() {

        Integer yesterdayactive = findyesterdayactive();

        long time = date.getTime();
        long l = time - (2 * days);
        Date date = new Date(l);
        String format = DashboardService.format.format(date);
        Integer qtactive = dashboardDao.findactive(format);


        String result = null;

        if (yesterdayactive > qtactive) {
            long i = yesterdayactive - qtactive;
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMaximumFractionDigits(0);
            result = numberFormat.format((float) i / (float) qtactive * 100);
        } else if (qtactive > yesterdayactive) {
            long i = qtactive - yesterdayactive;
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMaximumFractionDigits(0);
            result ="-"+ numberFormat.format((float) i / (float) qtactive * 100);
        } else {
            result = "0";
        }
        return Integer.parseInt(result);

    }

    private Integer findyesterdayactive() {
        long time = date.getTime();
        long l = time - days;
        Date date = new Date(l);

        String format = DashboardService.format.format(date);
        Integer findactive = dashboardDao.findactive(format);

        return findactive;

    }

    private Integer findtodayactiverate() {
        Integer findtodayactive = findtodayactive();

        long time = date.getTime();
        long l = time - days;
        Date date1 = new Date(l);
        String yesterday = DashboardService.format.format(date1);
        //查询昨天用户登陆次数
        Integer yesterdayactice = dashboardDao.findactive(yesterday);
        String result = null;

        if (findtodayactive > yesterdayactice) {
            long i = findtodayactive - yesterdayactice;
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMaximumFractionDigits(0);
            result = numberFormat.format((float) i / (float) yesterdayactice * 100);
        } else if (yesterdayactice > findtodayactive) {
            long i = yesterdayactice - findtodayactive;
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMaximumFractionDigits(0);
            result ="-"+ numberFormat.format((float) i / (float) yesterdayactice * 100);
        } else {
            result = "0";
        }
        return Integer.parseInt(result);

    }

    private Integer findtodayactive() {
        String today = DashboardService.format.format(date);
        Integer findtodayactive = dashboardDao.findactive(today);
        return findtodayactive;

    }

    private Integer findtodayloginrate() {

        //今日用户登录次数
        Integer findtodaylogin = findtodaylogin();
        long time = date.getTime();
        long l = time - days;
        Date date1 = new Date(l);
        String yesterday = DashboardService.format.format(date1);
        //查询昨天用户登陆次数
        Integer yesterdaylogin = dashboardDao.findlogin(yesterday);
        String result = null;

        if (findtodaylogin > yesterdaylogin) {
            long i = findtodaylogin - yesterdaylogin;
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMaximumFractionDigits(0);
            result = numberFormat.format((float) i / (float) yesterdaylogin * 100);
        } else if (yesterdaylogin > findtodaylogin) {
            long i = yesterdaylogin - findtodaylogin;
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMaximumFractionDigits(0);
            result ="-"+ numberFormat.format((float) i / (float) yesterdaylogin * 100);
        } else {
            result = "0";
        }
        return Integer.parseInt(result);
    }

    private Integer findtodaylogin() {
        String format = DashboardService.format.format(date);
        Integer login = dashboardDao.findlogin(format);
        return login;
    }

    private Integer findtodayrate() {
        //今天的新增用户
        String today = DashboardService.format.format(date);
        Integer todaynewaddnum = dashboardDao.findtodaynewadd(today);

        long time = date.getTime();
        long l = time - days;
        Date date1 = new Date(l);
        String yesterday = DashboardService.format.format(date1);
        Integer yesterdaynum = dashboardDao.findyesterdaynewadd(yesterday);

        String result = null;
        if (todaynewaddnum > yesterdaynum) {
            long i = todaynewaddnum - yesterdaynum;
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMaximumFractionDigits(0);
            result = numberFormat.format((float) i / (float) yesterdaynum * 100);
        } else if (yesterdaynum > todaynewaddnum) {
            long i = yesterdaynum - todaynewaddnum;
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMaximumFractionDigits(0);
            result = "-"+numberFormat.format((float) i / (float) yesterdaynum * 100);
        } else {
            result = "0";
        }
        return Integer.parseInt(result);
    }

    private Integer findtodaynewadd() {

        String today = DashboardService.format.format(date);
        Integer findtodaynewadd = dashboardDao.findtodaynewadd(today);
        return findtodaynewadd;

    }

    private Integer find7BeforeActive() {

        long time = date.getTime();
        long l = time - (days * 7);

        String nowdateString = DashboardService.format.format(date);
        String before7dateString = DashboardService.format.format(l);

        Integer integer = dashboardDao.find7BeforeActive(before7dateString, nowdateString);
        return integer;
    }


    private Integer findin30dayactive() {

        long time = date.getTime();
        long months = time - (days * 30);
        Date monthsdate = new Date(months);

        String monthsString = format.format(monthsdate);
        String nowString = format.format(date);
        Integer integer = dashboardDao.find30BeforeActive(monthsString, nowString);
        return integer;
    }



}
